/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.display {
	import com.googlecode.milib.base.MLBroadcastClass;

	import flash.display.MovieClip;

	/**
	 * @author Marek Brun
	 */
	public class DuplicatedMCSNumberController extends MLBroadcastClass {

		/*DATA:	{
			mc:MovieClip
			index:Number
		}*/
		public const event_NewMC : String = 'NewMC';
		
		/*DATA:	{
			mc:MovieClip
			index:Number
		}*/
		public const event_MCRemoved : String = 'MCRemoved';
		
		/*DATA:	{
			mc:MovieClip
			index:Number
		}*/
		public const event_MCAdded : String = 'MCAdded';
		
		private var duplicator:MCDuplicator;
		private var visibleMCS:Array;
		private var allMCS:Array;
		private var parentMC:MovieClip;

		public function DuplicatedMCSNumberController(duplicator:MCDuplicator) {
			this.duplicator=duplicator;
			allMCS=duplicator.getAllMCS();
			parentMC=allMCS[0].parent;
			var i:uint;
			var loopMC:MovieClip;
			for(i=0;i<allMCS.length;i++){
				loopMC=allMCS[i];
				loopMC.parent.removeChild(loopMC);
			}
			allMCS=[];
			visibleMCS=[];
			
		}
		
		public function setMCSNumber(sum:uint):void {
			var i:uint;
			var loopMC:MovieClip;
			
			for(i=sum;i<visibleMCS.length;i++){
				loopMC=visibleMCS[i];
				parentMC.removeChild(loopMC);
				visibleMCS.splice(i, 1); i--;
				broadcastEvent(event_MCRemoved, {mc:loopMC, index:i});
			}
			
			for(i=visibleMCS.length;i<sum;i++){
				if(!allMCS[i]){
					allMCS[i]=duplicator.getNewMC();
					broadcastEvent(event_NewMC, {mc:allMCS[i], index:i});
				}
				loopMC=allMCS[i];
				parentMC.addChild(loopMC);
				visibleMCS.push(loopMC);
				broadcastEvent(event_MCAdded, {mc:loopMC, index:i});
			}
		}
		
		public function getCurrentVisibleMCS():Array {
			return visibleMCS;
		}
		
		public function getCurrentVisibleMCSSum():uint {
			return visibleMCS.length;
		}
		
		public function addOne():void {
			setMCSNumber(visibleMCS.length+1);
		}
	}
}
